$(function(){

    var stch=false;
	//钱包充值
	$(document).on('click', '#js-recharge', function(e){
		$(".content-box").html("");
		var totalMoney = $('select').val();
		var _token = $("input[name='_token']").val();
		// var url = jumpUrl+"/wallet/recharge";
		var loading = layer.msg('加载中...', {icon: 16});
		var params = {};
		params.device = 'pc';
		params.channel = 'wx_pub_qr';
		params.amount = totalMoney*100;
		params.subject = '钱包充值';
		params.body = '金额：'+totalMoney;
		params.product_id = 'wallet';
		params.current_user_id = money_in_user_id;
		params.metadata = {};
		params.metadata.pay_type = 'wallet_recharge';
		params.metadata.user_id = money_in_user_id;
		console.info(params);
		var wechat_qr_params_url = jumpUrl+"/payment_gateway/charge";
		var qr_code_url;
	    $.post(wechat_qr_params_url,params,function(data){
	      },'json').error(function(data) {
	          var obj = $.parseJSON(data.responseText);
	          layer.msg(obj.error_messages);
	      }).success(function(data) {
	    	  console.info('charge',data);
	      	  qr_code_url = data.credential.wx_pub_qr;
	      	  charge_id = data.id;
	      	  qr_payment_popup();
	      	  check_payment(charge_id);
	      	  var str = ''
	      	  str +='<img src="http://paysdk.weixin.qq.com/example/qrcode.php?data='+qr_code_url+'" style="width:250px;height:250px;" />';
	      	  str +='<p style="text-align:center;font-size:20px;">[ 扫描二维码支付 ]</p>';
	      	$(".content-box").append(str);
	      });
		stopDefault(e);
		
	});
	function check_payment(charge_id){
		var t1;
		var sum =0;
		function update_notify(){
				sum++;
				if(sum>600){window.clearInterval(t1);return false;}
				if(sum>180){
					m = sum%10;
					if(m!=0){return false;}
				}
				$(".sum").html(sum);

				var payment_query_url = jumpUrl + '/payment_gateway/query/'+charge_id;
			    $.get(payment_query_url, function(data){
			          
		        }, "json").error(function(data) {
	                var status_code = $.parseJSON(data.responseText);
	                layer.msg(status_code.message);
		        }).success(function(data) {
					console.log(data);
		            var obj = data;
		            if(obj.paid==true) {
		            	layer.msg("充值成功");
			            window.location.href = jumpUrl + '/center/customer/wallet';
			        }
		        });
			}
			t1 = window.setInterval(function() {
				popup_visible = $(".content-box").is(":visible");
				if (popup_visible) {
					update_notify();
				}
				console.log('isvisible', $(".content-box").is(":visible"));
			},1000);

			window.onblur = function(){
				clearInterval(t1);
			}

			window.onfocus = function(){
				t1 = setInterval(function(){
					popup_visible = $(".content-box").is(":visible");
					if (popup_visible) {
						update_notify();
					}
				}, 1000 );
			}
	};
	// 微信扫码付费弹出框
	function qr_payment_popup(){
	 	var Popup02 = $(".content-box");
	 	layer.open({
          type: 1, //基本层类型  可传入的值有：0（信息框，默认）1（页面层）2（iframe层）3（加载层）4（tips层）。 若你采用layer.open({type: 1})方式调用，则type为必填项（信息框除外）
          title: false, //标题
          closeBtn: true,  //关闭按钮
          shade:0.3,  //遮罩默认是0.3透明度
          area: ['250px', '300px'],
          skin: 'yourclass', //样式类名
          content: Popup02 //内容
        });
        // if(isFirefox=navigator.userAgent.indexOf("Firefox")>0){
        //   $(".layui-layer").css('top','100px');
        // } 
	};
	
	//钱包提现
	$(document).on('click', '#js-withdraw', function(e){
		var form = $('#withdraw_form').serialize();
		var url = jumpUrl+"/wallet/withdraw";
		if(stch == false){
			stch = true;
			$.post(url,form,function(data){
				
			}, 'json').error(function(data){
		          var obj = $.parseJSON(data.responseText);
		          $.each(obj.error_messages, function(i, item){
		            layer.msg(item[0]);
		            stch=false;
		          });
			}).success(function(data) {alert('here');
		          layer.msg("提现申请已提交，请等待审核");
		          $("#money").text(data.data.money+".00");
		          $(':input','#withdraw_form').not('textarea :submit, :reset, :hidden').val('');
	              stch=false;
		      });
		}
		stopDefault(e);
	});
	
	//送心意
	
	//选择付款方式
	$('.icon02').click(function(){
	    $('.icon02').removeClass('icon04');
	    $(this).addClass('icon04');
	});
	//付款请求
	$(document).on('click', '#js-pay', function(e){
	    var url = $('.icon04').attr('data-href');
		var _token = $("input[name='_token']").val();
		var money = $("input[name='money']").val();
		var user_id = $("input[name='user_id']").val();
		if(stch == false){
			stch=true;
		    $.post(url,{"money":money,"_token":_token,"user_id":user_id},function(data){
		      },'json').error(function(data) {
		    	  // console.info(data.data);
		          var obj = $.parseJSON(data.responseText);
		          $.each(obj.error_messages, function(i, item){
		            layer.msg(item[0]);
		            stch=false;
		          });
		      }).success(function(data) {
		          layer.msg("送心意成功");
		          $("#money").text(data.data.money+"");
		          $('#form-money').val('');
		          
		          stch=false;
		          //window.location.href=jumpevaluation;
		      });
		}
	      stopDefault(e);
		});

});
